package com.course.web.biz;

import com.course.domain.enums.Role;
import com.course.domain.model.Account;
import com.course.domain.model.Teacher;
import com.course.domain.service.UserService;
import com.course.web.model.TeacherVM;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by Justin on 2017/6/3.
 */
@Component
public class WebTeacherBiz {

    private final UserService userService;

    @Autowired
    public WebTeacherBiz(UserService userService) {
        this.userService = userService;
    }

    public TeacherVM create(TeacherVM vm) {
        Teacher teacher = userService.createTeacher(vm.getUsername(), vm.getPassword(), toTeacher(vm));
        vm.setTeacherId(teacher.getId());
        vm.setAccountId(teacher.getAccountId());
        return vm;
    }

    public TeacherVM update(TeacherVM vm) {
        userService.updateAccount(toAccount(vm));
        userService.updateTeacher(toTeacher(vm));
        return vm;
    }

    public TeacherVM delete(TeacherVM vm) {
        userService.deleteTeacher(toTeacher(vm));
        return vm;
    }

    public List<TeacherVM> list() {
        List<Teacher> teacherList = userService.listTeacher();
        List<Integer> accountIdList = Lists.transform(teacherList, Teacher::getAccountId);
        Map<Integer, Account> accountMap = Maps.uniqueIndex(userService.findAccount(accountIdList), Account::getId);
        return Lists.transform(teacherList, teacher -> transform(teacher, accountMap));
    }

    private TeacherVM transform(Teacher teacher, Map<Integer, Account> accountMap) {
        Account account = accountMap.get(teacher.getAccountId());
        TeacherVM vm = new TeacherVM();
        vm.setTeacherId(teacher.getId());
        vm.setAccountId(account.getId());
        vm.setUsername(account.getUsername());
        vm.setPassword(account.getPassword());
        vm.setName(teacher.getName());
        return vm;
    }

    private Account toAccount(TeacherVM vm) {
        Account account = new Account();
        account.setId(vm.getAccountId());
        account.setRole(Role.TEACHER);
        account.setUsername(vm.getUsername());
        account.setPassword(vm.getPassword());
        account.setOAuthWx("");
        account.setStatus(1);
        return account;
    }

    private Teacher toTeacher(TeacherVM vm) {
        Teacher teacher = new Teacher();
        teacher.setId(vm.getTeacherId());
        teacher.setAccountId(vm.getAccountId());
        teacher.setName(vm.getName());
        teacher.setStatus(1);
        return teacher;
    }
}
